package com.quanyan.place.service.impl;

import cn.bailingniao.api.mq.OrderSale;
import cn.bailingniao.api.mq.SportsMqTopic;
import cn.bailingniao.api.mq.UserScheduleMsg;
import com.google.common.base.Function;
import com.google.common.collect.ImmutableMultiset;
import com.google.common.collect.Lists;
import com.quanyan.api.APIRequest;
import com.quanyan.api.APIResponse;
import com.quanyan.assets.request.ReqCoupon;
import com.quanyan.assets.response.RespOrderCoupon;
import com.quanyan.assets.service.CouponService;
import com.quanyan.common.utils.ObjectUtil;
import com.quanyan.mq.client.QcMsgClient;
import com.quanyan.mq.client.reqeust.MqRequestMsg;
import com.quanyan.place.entity.*;
import com.quanyan.place.entity.dto.ReqCouponDTO;
import com.quanyan.place.mapper.TbBizPlaceOrderItemMapper;
import com.quanyan.place.mapper.TbBizPlaceOrderMapper;
import com.quanyan.place.mapper.TbBizPlaceUnitSalePlanMapper;
import com.quanyan.place.service.CommonService;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;


/**
 * Created by zhaohui on 2017/5/10.
 */
@Service
public class CommonServiceImpl implements CommonService {

    private static final org.slf4j.Logger logger = LoggerFactory.getLogger(CommonServiceImpl.class);
    @Autowired
    private CouponService couponService;

    @Autowired
    TbBizPlaceOrderMapper tbBizPlaceOrderMapper;

    @Autowired
    private QcMsgClient mqSportsClient;

    @Autowired
    private TbBizPlaceOrderItemMapper tbBizPlaceOrderItemMapper;

    @Autowired
    private TbBizPlaceUnitSalePlanMapper tbBizPlaceUnitSalePlanMapper;
    /**
     * 获取优惠券列表
     * @param reqCouponDTO
     * @return
     */
    @Override
    public APIResponse<RespOrderCoupon> getCouponList(ReqCouponDTO reqCouponDTO) {
        APIRequest<ReqCoupon> apiReqCouponRequest = new APIRequest<>();
        ReqCoupon reqCoupon = new ReqCoupon();
        BeanUtils.copyProperties(reqCouponDTO,reqCoupon);

        apiReqCouponRequest.setVer(reqCouponDTO.getVer());
        apiReqCouponRequest.setData(reqCoupon);
        APIResponse<RespOrderCoupon> apiCouponResponse = null;
        try {
            apiCouponResponse = couponService.getOrderCouponList(apiReqCouponRequest);
        } catch (Exception e) {
            logger.error("获取优惠券列表失败：" + apiCouponResponse.getErrmsg());
            e.printStackTrace();
        }
        return apiCouponResponse;
    }

    @Override
    public void mqSendSportService(String placeOrderId, Integer status) {
        logger.warn("mqSendSportService：{}",placeOrderId);
        List<TbBizPlaceOrder> placeOrderList = this.getPlaceOrder(placeOrderId);
        if (null != placeOrderList && placeOrderList.size()>0) {
            logger.info("sports mq ============================================>start{}", placeOrderList.get(0).toString());
            List<TbBizPlaceOrderItem> orderItems = this.getPlaceOrderItem(placeOrderId);

            UserScheduleMsg userScheduleMsg = new UserScheduleMsg();
            TbBizPlaceOrder placeOrder = placeOrderList.get(0);
            userScheduleMsg.setOrderNo(placeOrder.getPlaceOrderId());
            userScheduleMsg.setPlaceId(placeOrder.getPlaceId());
            userScheduleMsg.setUid(placeOrder.getUid());
            userScheduleMsg.setCategoryId(placeOrder.getCategoryId());
            userScheduleMsg.setOrderStatus(placeOrder.getOrderStatus().intValue());
            userScheduleMsg.setType(placeOrder.getUseType().intValue());
            if (placeOrder.getDebit() != null){
                userScheduleMsg.setPrice(placeOrder.getDebit().doubleValue());
            }
            if (status == 1){
                userScheduleMsg.setOperation(SportsMqTopic.OperationType.confirm);
            }else if (status == 2){
                userScheduleMsg.setOperation(SportsMqTopic.OperationType.cancel);
            }
            if (orderItems != null && orderItems.size() > 0 ){
                List<Integer> salePlaceId = new ArrayList<>();
                salePlaceId.addAll(this.getSalePlanIdList(orderItems));
                List<TbBizPlaceUnitSalePlan> salePlanList = this.getPlaceSale(salePlaceId);
                userScheduleMsg.setExplainDate(orderItems.get(0).getConsumeTime());
                List<OrderSale> list = new ArrayList<>();
                for (TbBizPlaceOrderItem tbBizPlaceOrderItem :orderItems){
                    OrderSale orderSale = new OrderSale();
                    orderSale.setStartTime(tbBizPlaceOrderItem.getStartTime());
                    orderSale.setEndTime(tbBizPlaceOrderItem.getEndTime());
                    orderSale.setPlaceNum(tbBizPlaceOrderItem.getSaleId());
                    for (TbBizPlaceUnitSalePlan tbBizPlaceUnitSalePlan : salePlanList){
                        if (tbBizPlaceUnitSalePlan.getId().intValue() == tbBizPlaceOrderItem.getUnitSalePlanId()){
                            orderSale.setPlaceNum(tbBizPlaceUnitSalePlan.getPlaceUnitName());
                            break;
                        }
                    }
                    list.add(orderSale);
                    userScheduleMsg.setOrderSales(list);
                }
            }
            userScheduleMsg.setType(placeOrder.getUseType().intValue());
            logger.info("sports mq ============================================>end{}",userScheduleMsg.toString());
            MqRequestMsg mqRequestMsg = new MqRequestMsg();
            mqRequestMsg.setMsgId(String.valueOf(System.currentTimeMillis()));
            mqRequestMsg.setTopic(SportsMqTopic.SPORTS_MQ_TOPIC_SCHEDULES);
            mqRequestMsg.setTag(SportsMqTopic.SPORTS_MQ_TAG_SCHEDULES);
            mqRequestMsg.setBody(ObjectUtil.toByteArray(userScheduleMsg));
            byte [] bytes = ObjectUtil.toByteArray(userScheduleMsg);
            UserScheduleMsg userScheduleMsg1 = (UserScheduleMsg)ObjectUtil.toObject(bytes);
            logger.info("sports mq ===========================================================================================================================================================》{}",userScheduleMsg1.toString());
            mqSportsClient.asyncSend(mqRequestMsg);
        }

    }

    @Override
    public List<TbBizPlaceOrder> getPlaceOrder(String placeOrderId) {
        TbBizPlaceOrderExample placeOrderExample = new TbBizPlaceOrderExample();
        TbBizPlaceOrderExample.Criteria placeOrderCriteria =  placeOrderExample.createCriteria();
        placeOrderCriteria.andPlaceOrderIdEqualTo(placeOrderId);
        List<TbBizPlaceOrder> placeOrderList = tbBizPlaceOrderMapper.selectByExample(placeOrderExample);
        if (null != placeOrderList && placeOrderList.size()>0){
            return placeOrderList;
        }
        return null;
    }

    public List<TbBizPlaceOrderItem> getPlaceOrderItem(String placeOrderId){
        TbBizPlaceOrderItemExample itemExample = new TbBizPlaceOrderItemExample();
        TbBizPlaceOrderItemExample.Criteria criteria = itemExample.createCriteria();
        criteria.andPlaceOrderIdEqualTo(placeOrderId);
        return  tbBizPlaceOrderItemMapper.selectByExample(itemExample);

    }

    public List<TbBizPlaceUnitSalePlan> getPlaceSale(List<Integer> saleIds){
        TbBizPlaceUnitSalePlanExample itemExample = new TbBizPlaceUnitSalePlanExample();
        TbBizPlaceUnitSalePlanExample.Criteria criteria = itemExample.createCriteria();
        criteria.andIdIn(saleIds);
        return tbBizPlaceUnitSalePlanMapper.selectByExample(itemExample);
    }


    //list 按属性生成一个新的 list
    public ImmutableMultiset<Integer> getSalePlanIdList( List<TbBizPlaceOrderItem>  lst) {
        return ImmutableMultiset.copyOf(Lists.transform(lst, new Function<TbBizPlaceOrderItem, Integer>() {
                    @Override
                    public Integer apply(TbBizPlaceOrderItem input) {
                        return input.getUnitSalePlanId();
                    }
                }
        ));
    }
}
